﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;

namespace miniCCR
{


    public abstract class GObjectThread : GObject
    {


        static Thread _Thread;

        Queue<Operation> _ThreadQueue = new Queue<Operation>();

        public GObjectThread() : base()
        {
            //thre            

        }


        public override void Init()
        {

            if (_Thread == null)
            {
                _Thread = new Thread(WorkerThread);
                _Thread.Start();
            }

        }

        public abstract void WorkerThread();



        
             

        public override void Post(Operation o)
        {

            // 락쳐야함
            lock (this)
            {
                _ThreadQueue.Enqueue(o);
            }
            

            //foreach (var com in _ComponentList.Values)
            //{
            //    if( com.GetType().ToString() == o._ToComID)
            //        com.Post(o);
            //}
        }


        public void Update()
        {

            Operation o;

            while ((o = GetOP()) != null)
            {
                foreach (var com in _ComponentList.Values)
                {
                    if( o._ToComID == 0)
                        com.Post(o);
                    else if (com._ComID == o._ToComID)
                        com.Post(o);
                }
            }

        }

        public Operation GetOP()
        {
            lock (this)
            {
                if (_ThreadQueue.Count == 0)
                    return null;

                return _ThreadQueue.Dequeue();
            }

            

            // 락쳐야함
            

            //foreach (var com in _ComponentList.Values)
            //{
            //    if( com.GetType().ToString() == o._ToComID)
            //        com.Post(o);
            //}
        }



    }


}
